/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package intershopxssscanner.filters;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Willem
 */
public class FilterManager {

    public static String COUNT = "count";
    private Properties defaultProps = new Properties();
    private ArrayList<Filter> filterchain = new ArrayList<Filter>();

    public FilterManager() {
        FileInputStream in = null;
        try {
            in = new FileInputStream("FilterManager.properties");
            defaultProps.load(in);
            in.close();
        } catch (IOException ex) {
            Logger.getLogger(FilterManager.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                in.close();
            } catch (IOException ex) {
                Logger.getLogger(FilterManager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void loadFilterChain() {
        Integer count = Integer.valueOf(defaultProps.getProperty(COUNT));
        Filter f;

        for (int i = 0; i < count; i++) {
            String filtername = defaultProps.getProperty(Filter.PREFIX + i);

            if (filtername == null) {
                Logger.getLogger(FilterManager.class.getName()).log(Level.INFO, "filter 404: f" + i);
                continue;
            }

            if ("RemoveIncludeLine".equalsIgnoreCase(filtername)) {
                f = new RemoveIncludeLineFilter();
                addtoChain(f, i);
            } else if ("TrimFilter".equalsIgnoreCase(filtername)) {
                f = new TrimFilter();
                addtoChain(f, i);
            } else if ("ReplaceStringFilter".equalsIgnoreCase(filtername)) {
                f = new ReplaceStringFilter();
                addtoChain(f, i);
            }
            else{
                Logger.getLogger(FilterManager.class.getName()).log(Level.INFO, "Unknown filter" + filtername);
            }
        }
    }

    private void addtoChain(Filter f, int id) {
        f.loadSettings(defaultProps, String.valueOf(id));
        f.setID(id);
        filterchain.add(f);

        Logger.getLogger(FilterManager.class.getName()).log(Level.INFO, "filter loaded: " + f);
    }
    
    
    public ArrayList<String> doChain(ArrayList<String> data) {
        ArrayList<String> output = new ArrayList<String>();
        
        for (Filter filter : filterchain) {
            data = filter.doFilter(data);            
        }
        
        return data;
    }
}
